layui.use(['form','layer','layedit','laydate','upload','util'],function(){
    var form = layui.form
        layer = parent.layer === undefined ? layui.layer : top.layer,
        laypage = layui.laypage,
        upload = layui.upload,
        layedit = layui.layedit,
        $ = layui.jquery;
	var util = layui.util,
		api = util.api;

	
    var id = util.getQueryString("id");
    
	util.request(api.getEquipmentPageInfo).then(function(res) {
		var s="";
		$.each(res.result.equipmentCategoryList, function(index,value) {
			s+=`<input type="radio" name="equipment" value="${value.id}" title="${value.name}" lay-skin="primary" />`
		});
		$('.equipmentCategoryInput').html(s);
		
		
	    if(id){
			util.request(api.getEquipmentById,{
				id:id
			}).then(function(res) {
				$('.name').val(res.result.equipment.name);
				$('.describe').val(res.result.equipment.name);
				$('.image').attr('src',api.imageHost+res.result.equipment.imageUrl);
				$('.image').attr('imgName',res.result.equipment.imageUrl);
				$(`.equipmentCategoryInput input[value=${res.result.equipment.category}]`).attr('checked',true);
				form.render();
			})
	   	}else{
			form.render();
	    }
	});
	
	
	$('.submitBtn').click(function(){
		if($('.name').val().trim()==""){
			layer.alert("名称不能为空"); return;
		}
		if($('.describe').val().trim()==""){
			layer.alert("描述不能为空"); return;
		}
		if(typeof($('.image').attr('imgName'))=="undefined"){
			layer.alert("图片不能为空"); return;
		}
		if(typeof($(`.equipmentCategoryInput input[name=equipment]:checked`).val())=="undefined"){
			layer.alert("选择设备类型"); return;
		}
		if(id){
			var data={
				id:id,
				name:$('.name').val(),
				describe:$('.describe').val(),
				imageUrl:$('.image').attr('imgName'),
				category:$(`.equipmentCategoryInput input[name=equipment]:checked`).val()
			}
			console.log(data)
			util.request(api.updateEquipment,JSON.stringify(data),"application/json").then(function(res) {
				layer.alert("操作成功",function(index){
					window.parent.location.reload();
					layer.close(index);
				})
			})
		}else{
			var data={
				name:$('.name').val(),
				describe:$('.describe').val(),
				imageUrl:$('.image').attr('imgName'),
				category:$(`.equipmentCategoryInput input[name=equipment]:checked`).val()
			}
			console.log(data)
			util.request(api.addEquipment,JSON.stringify(data),"application/json").then(function(res) {
				layer.alert("操作成功",function(index){
					window.parent.location.reload();
					layer.close(index);
				})
			})
		}
	})
	
    
    upload.render({
        elem: '#image',
        url:api.uploadImage,
        accept: 'images',
        done: function(res){
			$('.image').attr('src',api.imageHost+res.result.fileName);
			$('.image').attr('imgName',res.result.fileName);
        }
    });
    
})